package com.example.feature.demo.service.impl;

import com.example.feature.demo.constant.ErrorCodeConstant;
import com.example.feature.demo.service.FileService;
import com.example.feature.demo.vo.HYMember;
import com.example.feature.demo.vo.HYMemeberList;
import com.github.liaochong.myexcel.core.SaxExcelReader;
import com.zhou.common.exception.CommonException;
import com.zhou.common.exception.ExcelValidException;
import com.zhou.common.util.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.io.IOException;
import java.util.List;
import java.util.Set;

/**
 * FileServiceImpl
 *
 * @author zhouxianfeng
 * @date 2021-5-17
 */
@Service
public class FileServiceImpl implements FileService {

    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Autowired
    private Validator validator;

    @Autowired
    private RedisUtils redisUtils;

    private static final String IMPORT_EXCEL_BATCH_NO = "import_excel_batch_no";

    @Override
    public void batchImport(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (!".xlsx".equals(fileType)) {
            throw new CommonException(ErrorCodeConstant.FILETYPE_NOT_EQUAL_XLSX);
        }
        List<HYMember> list;
        try {
            list = SaxExcelReader.of(HYMember.class)
                    .sheet(0)
                    .rowFilter(row -> row.getRowNum() > 0)
                    .read(file.getInputStream());
            Set<ConstraintViolation<HYMemeberList>> validate = validator.validate(new HYMemeberList(list), Default.class);
            if (validate.size() > 0) {
                throw new ExcelValidException(validate);
            }
        } catch (IOException e) {
            logger.error("", e);
            throw new CommonException("文件读取失败");
        }
        if (list.size() > 0) {
            String lastBatchNo = (String) redisUtils.get(IMPORT_EXCEL_BATCH_NO);
            String currBatchNo = list.get(0).getBatchNo();
            if (currBatchNo.equals(lastBatchNo)) {
                throw new CommonException("批次号一致,重复导入");
            }
            redisUtils.set(IMPORT_EXCEL_BATCH_NO, currBatchNo);
        }
    }
}
